<template>
  <div class="app-container">
    <div class="search-bar">
      <!-- 拆线呢区域 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable width="190px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="文件存储桶" prop="bucketName">
          <el-input v-model="queryParams.bucketName" placeholder="请输入文件存储桶" clearable width="190px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="原始文件名" prop="original">
          <el-input v-model="queryParams.original" placeholder="请输入原始文件名" clearable width="190px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="文件类型" prop="type">
          <el-input v-model="queryParams.type" placeholder="请输入文件类型" clearable width="190px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" icon="search" v-hasPerm="'sys_file_view'" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- 操作区域 -->
      <div class="mb-10px">
        <!-- <el-button type="success" icon="plus" @click="handleOpenDialog()">上传文件</el-button> -->
        <!-- <el-button
          type="danger"
          :disabled="selectIds.length === 0"
          icon="delete"
          @click="handleDelete()"
        >
          删除
        </el-button> -->
      </div>
      <!-- @selection-change="handleSelectionChange" -->

      <el-table v-loading="loading" :data="FileList" row-key="id" border height="calc(100vh - 350px)"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="fileName" label="文件名称" min-width="200" /> -->
        <el-table-column prop="original" label="原始文件名" min-width="240" show-overflow-tooltip />
        <el-table-column prop="bucketName" label="文件存储桶" width="125" />
        <el-table-column prop="fileSize" label="文件大小" width="125" />
        <el-table-column prop="type" label="文件类型" width="120" />
        <el-table-column prop="updateTime" label="修改时间" width="170" />
        <el-table-column prop="createBy" label="创建人" width="150" />
        <el-table-column prop="updateBy" label="修改人" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="170" />
        <el-table-column label="操作" fixed="right" align="left" width="180">
          <template #default="scope">
            <el-button type="primary" link size="small" icon="download" v-hasPerm="'sys_file_download'"
              @click.stop="handleDownload(scope.row)">
              下载
            </el-button>
            <el-button type="danger" link size="small" icon="delete" v-hasPerm="'sys_file_del'"
              @click.stop="handleDelete([scope.row.id])">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div v-if="pageInfo.total > 0" class="pager-container">
        <pagination v-model:total="pageInfo.total" v-model:page="pageInfo.current" v-model:limit="pageInfo.size"
          @pagination="handleQuery" />
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" title="文件上传" width="400px" :close-on-click-modal="false"
      @closed="handleCloseDialog">
      <div>
        <el-upload ref="fileuploadRef" drag :on-change="handleUploadChange" style="margin: 0 auto"
          :accept="accept.join(',')" :auto-upload="false" :multiple="false" :limit="1" :show-file-list="true">
          <div class="fileUploadContent">
            <p>
              <el-icon class="el-icon--upload" size="50" color="#a8abb2"><upload-filled /></el-icon>
            </p>
            <div class="el-upload__text">
              拖拽或者
              <em style="color: #409eff">点击上传</em>
            </div>
          </div>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'File',
  inheritAttrs: false,
});
import { accept } from '@/utils/validate';
import FileAPI, { FileVO } from '@/api/system/file.api';
import { UploadFilled } from '@element-plus/icons-vue';
import { toRaw } from 'vue';
const queryFormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<FileVO>({});
const pageInfo = reactive({
  current: 1,
  size: 10,
  total: 0,
});
const dialog = reactive({
  title: '新增',
  visible: false,
});
const FileList = ref<FileVO[]>();
// delFlag	删除标记 0:正常,1:已删除

// 查询区域
function handleQuery() {
  loading.value = true;
  const param: any = {
    ...toRaw(queryParams),
    ...toRaw(pageInfo),
    current: pageInfo.current,
    size: pageInfo.size,
  };
  for (const key in param) {
    if (param[key] === undefined || param[key] === null || param[key] === '') {
      delete param[key];
    }
  }
  delete param.total;
  FileAPI.getList(param).then((data: any) => {
    FileList.value = data.records;
    pageInfo.total = data.total;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  pageInfo.current = 1;
  handleQuery();
}

// 处理选中项变化
// function handleSelectionChange(selection: any) {
//   selectIds.value = selection.map((item: any) => item.id);
// }

/**
 * 打开区域弹窗
 *
 * @param parentId 父区域ID
 * @param FileId 区域ID
 */
async function handleOpenDialog() {
  dialog.visible = true;
}

const handleDownload = (row: any) => {
  FileAPI.downloadFile(row.id, row.original).then((data: any) => { });
};
// 删除区域
function handleDelete(ids?: number[]) {
  if (!ids || ids.length === 0) {
    ElMessage.warning('请勾选删除项');
    return;
  }

  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(
    () => {
      loading.value = true;
      FileAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success('删除成功');
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info('已取消删除');
    }
  );
}
// 多选处理
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
}
const fileuploadRef = ref<any>(null);
// 提交区域表单
function handleSubmit() {
  if (!uploadFile) return;
  const formData = new FormData();
  formData.append('id', '' + Date.now());
  formData.append('file', uploadFile);
  console.log(formData);
  FileAPI.create(formData).then(() => {
    ElMessage.success('上传成功');
    fileuploadRef.value.clearFiles();
    uploadFile = null;
    dialog.visible = false;
    handleResetQuery();
  });
}
// 文件处理
let uploadFile: any = null;
function handleUploadChange(file: any) {
  uploadFile = file.raw;
}
onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
:deep(.el-upload--text) {
  width: 100%;
}

.fileUploadContent {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100px;
  width: 100%;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
}
</style>
